package it.uniroma3.dia.ia.textcategorization.datasource.odpdump;

import java.util.HashSet;
import java.util.Set;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public final class SubcategoriesFinderHandler extends DefaultHandler {

	private String path;
	private Set<String> subcategoriesNames = new HashSet<String>();

	private boolean categoryFound = false;
	private boolean subcategoriesFound = false;

	SubcategoriesFinderHandler(String path) {
		this.path = path;
	}

	@Override
	public void startElement(String uri, String localName, String qualifiedName,
			Attributes attributes) {
		if (this.categoryFound) {
			if (qualifiedName.equals("narrow") || qualifiedName.equals("narrow1")
					|| qualifiedName.equals("narrow2")) {
				String subcategoryName = attributes
						.getValue("r:resource");
				this.subcategoriesNames.add(subcategoryName);
			}
		} else {
			if (qualifiedName.equals("Topic")) {
				String categoryName = attributes.getValue("r:id");
				if (categoryName.equals(this.path)) {
					this.categoryFound = true;
				}
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (this.categoryFound) {
			if (qName.equals("Topic")) {
				this.subcategoriesFound = true;
				throw new SAXException();
			}
		}
	}

	boolean subcategoriesFound() {
		return this.subcategoriesFound;
	}

	Set<String> getSubcategoriesNames() {
		return subcategoriesNames;
	}

}
